Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Lists

Adding List items

Adding Elements and Lists in Python

Lists in Python are versatile and can grow dynamically. Here are various approaches to add elements or even entire lists:

1. Appending with append(x)

The most common way to add an element to the end of a list is using the append(x) method. It modifies the original list in-place.
Adding item in list using append() method fruits = ["apple", "banana"] fruits.append("cherry") print(fruits)

Output

["apple", "banana", "cherry"]

2. Extending with extend(iterable)

The extend(iterable) method efficiently adds all elements from an iterable (like another list, tuple, or string) to the end of the existing list. It modifies the original list in-place.
Adding element in list using extent() method in python fruits = ["apple", "banana", "cherry"] vegetables = ["carrot", "potato"] fruits.extend(vegetables) print(fruits)

Output

["apple", "banana", "cherry", "carrot", "potato"]

3. Insertion with insert(i, x)

The insert(i, x) method inserts a new element (x) at a specific index (i). Elements at and after the specified index are shifted one position to the right.
Adding item in list using insert() method numbers = [10, 20, 40] numbers.insert(2, 30) # Insert 30 at index 2 print(numbers)

Output

[10, 20, 30, 40]

4. Concatenation with the Plus Operator (+)

You can create a new list by combining (concatenating) two or more existing lists using the plus operator (+).
Merging two list using (+) operator in python fruits = ["apple", "banana"] vegetables = ["carrot", "potato"] combined_list = fruits + vegetables print(combined_list)

Output

["apple", "banana", "carrot", "potato"]

Choosing the Right Method

⯁ Adding a single element to the end: Use append. ⯁ Adding elements from another iterable to the end: Use extend. ⯁ Inserting an element at a specific position: Use insert. ⯁ Adding elements with transformations: Leverage list comprehensions. ⯁ Creating a new combined list: Use concatenation (+). Remember: ⯁ append and extend modify the original list. ⯁ insert modifies the original list by shifting elements. ⯁ List comprehensions and concatenation create new lists. ⯁ Consider efficiency (especially for large lists) when choosing between append and extend.

  📌TAGS

★python ★ list ★ methods

Tutorials